package com.gs.xbinfomytest.controller;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONArray;
import com.gs.xbinfomytest.config.ConstantUtils;
import com.gs.xbinfomytest.entity.SysMenu;
import com.gs.xbinfomytest.entity.SysUser;
import com.gs.xbinfomytest.log.LogRecord;
import com.gs.xbinfomytest.service.UserService;
import com.gs.xbinfomytest.util.MenuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Created : IntelliJ IDEA.
 * @ProjectName: xbinfomytest
 * @Package: com.gs.xbinfomytest.controller
 * @Author: guoshuai
 * @CreateDate: 2019/8/20 16:27
 * @Description: java类的作用描述
 * @Vsersion: 1.0
 */
@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping("/loginIn")
    @LogRecord(value = "用户登录")
    //@ResponseBody
    public String loginIn(RedirectAttributes model, String username, String password, String verify, HttpSession session){
        String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
        System.out.println("random:::"+random);
        if(verify==null || "".equals(verify) || !random.equals(verify.toLowerCase())){
            model.addFlashAttribute("loginMsg","验证码输入不正确！");
            return "redirect:/login";
        }else{
            password = SecureUtil.md5(password);
            SysUser sysUser = userService.findByUserNameAndPassword(username,password);
            if(sysUser == null){
                model.addFlashAttribute("loginMsg","用户不存在！");
                return "redirect:/login";
            }else{
                if("0".equals(sysUser.getStatus())){
                    List<SysMenu> list =userService.findByUserId(sysUser.getUserId());
                    List<SysMenu> mylist =     MenuUtils.getTreeMeauInfo(list);
                    session.setAttribute(ConstantUtils.MENU_SESSION_KEY, JSONArray.toJSONString(mylist));
                    session.setAttribute("menuInfo", JSONArray.toJSONString(mylist));
                    session.setAttribute("usernameInfo", sysUser.getUserName());
                    session.setAttribute(ConstantUtils.USER_SESSION_KEY, sysUser);
                    return "redirect:/index";
                }else{
                    model.addFlashAttribute("loginMsg","用户已经被禁用！");
                    return "redirect:/login";
                }


            }



        }


  }
    @RequestMapping("/loginout")
    @LogRecord(value = "用户退出登录")
    public String  loginout(HttpSession session){
        session.setAttribute("menuInfo", null);
        session.setAttribute("usernameInfo", null);
        session.setAttribute("user", null);
        return "redirect:/login";
    }



}
